home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / email / header.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  13.2 KB  |  411 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Header encoding and decoding functionality.'''
  5. __all__ = [
  6.     'Header',
  7.     'decode_header',
  8.     'make_header']
  9. import re
  10. import binascii
  11. import email.quoprimime as email
  12. import email.base64mime as email
  13. from email.errors import HeaderParseError
  14. from email.charset import Charset
  15. NL = '\n'
  16. SPACE = ' '
  17. USPACE = u' '
  18. SPACE8 = ' ' * 8
  19. UEMPTYSTRING = u''
  20. MAXLINELEN = 76
  21. USASCII = Charset('us-ascii')
  22. UTF8 = Charset('utf-8')
  23. ecre = re.compile('\n  =\\?                   # literal =?\n  (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset\n  \\?                    # literal ?\n  (?P<encoding>[qb])    # either a "q" or a "b", case insensitive\n  \\?                    # literal ?\n  (?P<encoded>.*?)      # non-greedy up to the next ?= is the encoded string\n  \\?=                   # literal ?=\n  (?=[ \\t]|$)           # whitespace or the end of the string\n  ', re.VERBOSE | re.IGNORECASE | re.MULTILINE)
  24. fcre = re.compile('[\\041-\\176]+:$')
  25. _max_append = email.quoprimime._max_append
  26.  
  27. def decode_header(header):
  28.     '''Decode a message header value without converting charset.
  29.  
  30.     Returns a list of (decoded_string, charset) pairs containing each of the
  31.     decoded parts of the header.  Charset is None for non-encoded parts of the
  32.     header, otherwise a lower-case string containing the name of the character
  33.     set specified in the encoded string.
  34.  
  35.     An email.errors.HeaderParseError may be raised when certain decoding error
  36.     occurs (e.g. a base64 decoding exception).
  37.     '''
  38.     header = str(header)
  39.     if not ecre.search(header):
  40.         return [
  41.             (header, None)]
  42.     decoded = []
  43.     dec = ''
  44.     for line in header.splitlines():
  45.         if not ecre.search(line):
  46.             decoded.append((line, None))
  47.             continue
  48.         
  49.         parts = ecre.split(line)
  50.         while parts:
  51.             unenc = parts.pop(0).strip()
  52.             if unenc:
  53.                 if decoded and decoded[-1][1] is None:
  54.                     decoded[-1] = (decoded[-1][0] + SPACE + unenc, None)
  55.                 else:
  56.                     decoded.append((unenc, None))
  57.             
  58.             if parts:
  59.                 (charset, encoding) = [ s.lower() for s in parts[0:2] ]
  60.                 encoded = parts[2]
  61.                 dec = None
  62.                 if encoding == 'q':
  63.                     dec = email.quoprimime.header_decode(encoded)
  64.                 elif encoding == 'b':
  65.                     
  66.                     try:
  67.                         dec = email.base64mime.decode(encoded)
  68.                     except binascii.Error:
  69.                         []
  70.                         []
  71.                         raise HeaderParseError
  72.                     except:
  73.                         []<EXCEPTION MATCH>binascii.Error
  74.                     
  75.  
  76.                 []
  77.                 if dec is None:
  78.                     dec = encoded
  79.                 
  80.                 if decoded and decoded[-1][1] == charset:
  81.                     decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1])
  82.                 else:
  83.                     decoded.append((dec, charset))
  84.             
  85.             del parts[0:3]
  86.     
  87.     return decoded
  88.  
  89.  
  90. def make_header(decoded_seq, maxlinelen = None, header_name = None, continuation_ws = ' '):
  91.     '''Create a Header from a sequence of pairs as returned by decode_header()
  92.  
  93.     decode_header() takes a header value string and returns a sequence of
  94.     pairs of the format (decoded_string, charset) where charset is the string
  95.     name of the character set.
  96.  
  97.     This function takes one of those sequence of pairs and returns a Header
  98.     instance.  Optional maxlinelen, header_name, and continuation_ws are as in
  99.     the Header constructor.
  100.     '''
  101.     h = Header(maxlinelen = maxlinelen, header_name = header_name, continuation_ws = continuation_ws)
  102.     for s, charset in decoded_seq:
  103.         if charset is not None and not isinstance(charset, Charset):
  104.             charset = Charset(charset)
  105.         
  106.         h.append(s, charset)
  107.     
  108.     return h
  109.  
  110.  
  111. class Header:
  112.     
  113.     def __init__(self, s = None, charset = None, maxlinelen = None, header_name = None, continuation_ws = ' ', errors = 'strict'):
  114.         """Create a MIME-compliant header that can contain many character sets.
  115.  
  116.         Optional s is the initial header value.  If None, the initial header
  117.         value is not set.  You can later append to the header with .append()
  118.         method calls.  s may be a byte string or a Unicode string, but see the
  119.         .append() documentation for semantics.
  120.  
  121.         Optional charset serves two purposes: it has the same meaning as the
  122.         charset argument to the .append() method.  It also sets the default
  123.         character set for all subsequent .append() calls that omit the charset
  124.         argument.  If charset is not provided in the constructor, the us-ascii
  125.         charset is used both as s's initial charset and as the default for
  126.         subsequent .append() calls.
  127.  
  128.         The maximum line length can be specified explicit via maxlinelen.  For
  129.         splitting the first line to a shorter value (to account for the field
  130.         header which isn't included in s, e.g. `Subject') pass in the name of
  131.         the field in header_name.  The default maxlinelen is 76.
  132.  
  133.         continuation_ws must be RFC 2822 compliant folding whitespace (usually
  134.         either a space or a hard tab) which will be prepended to continuation
  135.         lines.
  136.  
  137.         errors is passed through to the .append() call.
  138.         """
  139.         if charset is None:
  140.             charset = USASCII
  141.         
  142.         if not isinstance(charset, Charset):
  143.             charset = Charset(charset)
  144.         
  145.         self._charset = charset
  146.         self._continuation_ws = continuation_ws
  147.         cws_expanded_len = len(continuation_ws.replace('\t', SPACE8))
  148.         self._chunks = []
  149.         if s is not None:
  150.             self.append(s, charset, errors)
  151.         
  152.         if maxlinelen is None:
  153.             maxlinelen = MAXLINELEN
  154.         
  155.         if header_name is None:
  156.             self._firstlinelen = maxlinelen
  157.         else:
  158.             self._firstlinelen = maxlinelen - len(header_name) - 2
  159.         self._maxlinelen = maxlinelen - cws_expanded_len
  160.  
  161.     
  162.     def __str__(self):
  163.         '''A synonym for self.encode().'''
  164.         return self.encode()
  165.  
  166.     
  167.     def __unicode__(self):
  168.         '''Helper for the built-in unicode function.'''
  169.         uchunks = []
  170.         lastcs = None
  171.         for s, charset in self._chunks:
  172.             nextcs = charset
  173.             if uchunks:
  174.                 if lastcs not in (None, 'us-ascii'):
  175.                     if nextcs in (None, 'us-ascii'):
  176.                         uchunks.append(USPACE)
  177.                         nextcs = None
  178.                     
  179.                 elif nextcs not in (None, 'us-ascii'):
  180.                     uchunks.append(USPACE)
  181.                 
  182.             
  183.             lastcs = nextcs
  184.             uchunks.append(unicode(s, str(charset)))
  185.         
  186.         return UEMPTYSTRING.join(uchunks)
  187.  
  188.     
  189.     def __eq__(self, other):
  190.         return other == self.encode()
  191.  
  192.     
  193.     def __ne__(self, other):
  194.         return not (self == other)
  195.  
  196.     
  197.     def append(self, s, charset = None, errors = 'strict'):
  198.         """Append a string to the MIME header.
  199.  
  200.         Optional charset, if given, should be a Charset instance or the name
  201.         of a character set (which will be converted to a Charset instance).  A
  202.         value of None (the default) means that the charset given in the
  203.         constructor is used.
  204.  
  205.         s may be a byte string or a Unicode string.  If it is a byte string
  206.         (i.e. isinstance(s, str) is true), then charset is the encoding of
  207.         that byte string, and a UnicodeError will be raised if the string
  208.         cannot be decoded with that charset.  If s is a Unicode string, then
  209.         charset is a hint specifying the character set of the characters in
  210.         the string.  In this case, when producing an RFC 2822 compliant header
  211.         using RFC 2047 rules, the Unicode string will be encoded using the
  212.         following charsets in order: us-ascii, the charset hint, utf-8.  The
  213.         first character set not to provoke a UnicodeError is used.
  214.  
  215.         Optional `errors' is passed as the third argument to any unicode() or
  216.         ustr.encode() call.
  217.         """
  218.         if charset is None:
  219.             charset = self._charset
  220.         elif not isinstance(charset, Charset):
  221.             charset = Charset(charset)
  222.         
  223.         if charset != '8bit':
  224.             if isinstance(s, str):
  225.                 if not charset.input_codec:
  226.                     pass
  227.                 incodec = 'us-ascii'
  228.                 ustr = unicode(s, incodec, errors)
  229.                 if not charset.output_codec:
  230.                     pass
  231.                 outcodec = 'us-ascii'
  232.                 ustr.encode(outcodec, errors)
  233.             elif isinstance(s, unicode):
  234.                 for charset in (USASCII, charset, UTF8):
  235.                     
  236.                     try:
  237.                         if not charset.output_codec:
  238.                             pass
  239.                         outcodec = 'us-ascii'
  240.                         s = s.encode(outcodec, errors)
  241.                     continue
  242.                     except UnicodeError:
  243.                         continue
  244.                     
  245.  
  246.                 elif not False:
  247.                     raise AssertionError, 'utf-8 conversion failed'
  248.                 None<EXCEPTION MATCH>UnicodeError
  249.             
  250.         
  251.         self._chunks.append((s, charset))
  252.  
  253.     
  254.     def _split(self, s, charset, maxlinelen, splitchars):
  255.         splittable = charset.to_splittable(s)
  256.         encoded = charset.from_splittable(splittable, True)
  257.         elen = charset.encoded_header_len(encoded)
  258.         if elen <= maxlinelen:
  259.             return [
  260.                 (encoded, charset)]
  261.         if charset == '8bit':
  262.             return [
  263.                 (s, charset)]
  264.         if charset == 'us-ascii':
  265.             return self._split_ascii(s, charset, maxlinelen, splitchars)
  266.         fsplittable = charset.to_splittable(first)
  267.         fencoded = charset.from_splittable(fsplittable, True)
  268.         chunk = [
  269.             (fencoded, charset)]
  270.         return chunk + self._split(last, charset, self._maxlinelen, splitchars)
  271.  
  272.     
  273.     def _split_ascii(self, s, charset, firstlen, splitchars):
  274.         chunks = _split_ascii(s, firstlen, self._maxlinelen, self._continuation_ws, splitchars)
  275.         return zip(chunks, [
  276.             charset] * len(chunks))
  277.  
  278.     
  279.     def _encode_chunks(self, newchunks, maxlinelen):
  280.         chunks = []
  281.         for header, charset in newchunks:
  282.             if not header:
  283.                 continue
  284.             
  285.             if charset is None or charset.header_encoding is None:
  286.                 s = header
  287.             else:
  288.                 s = charset.header_encode(header)
  289.             if chunks and chunks[-1].endswith(' '):
  290.                 extra = ''
  291.             else:
  292.                 extra = ' '
  293.             _max_append(chunks, s, maxlinelen, extra)
  294.         
  295.         joiner = NL + self._continuation_ws
  296.         return joiner.join(chunks)
  297.  
  298.     
  299.     def encode(self, splitchars = ';, '):
  300.         """Encode a message header into an RFC-compliant format.
  301.  
  302.         There are many issues involved in converting a given string for use in
  303.         an email header.  Only certain character sets are readable in most
  304.         email clients, and as header strings can only contain a subset of
  305.         7-bit ASCII, care must be taken to properly convert and encode (with
  306.         Base64 or quoted-printable) header strings.  In addition, there is a
  307.         75-character length limit on any given encoded header field, so
  308.         line-wrapping must be performed, even with double-byte character sets.
  309.  
  310.         This method will do its best to convert the string to the correct
  311.         character set used in email, and encode and line wrap it safely with
  312.         the appropriate scheme for that character set.
  313.  
  314.         If the given charset is not known or an error occurs during
  315.         conversion, this function will return the header untouched.
  316.  
  317.         Optional splitchars is a string containing characters to split long
  318.         ASCII lines on, in rough support of RFC 2822's `highest level
  319.         syntactic breaks'.  This doesn't affect RFC 2047 encoded lines.
  320.         """
  321.         newchunks = []
  322.         maxlinelen = self._firstlinelen
  323.         lastlen = 0
  324.         for s, charset in self._chunks:
  325.             targetlen = maxlinelen - lastlen - 1
  326.             if targetlen < charset.encoded_header_len(''):
  327.                 targetlen = maxlinelen
  328.             
  329.             newchunks += self._split(s, charset, targetlen, splitchars)
  330.             (lastchunk, lastcharset) = newchunks[-1]
  331.             lastlen = lastcharset.encoded_header_len(lastchunk)
  332.         
  333.         return self._encode_chunks(newchunks, maxlinelen)
  334.  
  335.  
  336.  
  337. def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars):
  338.     lines = []
  339.     maxlen = firstlen
  340.     for line in s.splitlines():
  341.         line = line.lstrip()
  342.         if len(line) < maxlen:
  343.             lines.append(line)
  344.             maxlen = restlen
  345.             continue
  346.         
  347.         for ch in splitchars:
  348.             if ch in line:
  349.                 break
  350.                 continue
  351.         else:
  352.             maxlen = restlen
  353.         cre = re.compile('%s\\s*' % ch)
  354.         if ch in ';,':
  355.             eol = ch
  356.         else:
  357.             eol = ''
  358.         joiner = eol + ' '
  359.         joinlen = len(joiner)
  360.         wslen = len(continuation_ws.replace('\t', SPACE8))
  361.         this = []
  362.         linelen = 0
  363.         for part in cre.split(line):
  364.             curlen = linelen + max(0, len(this) - 1) * joinlen
  365.             partlen = len(part)
  366.             onfirstline = not lines
  367.             if ch == ' ' and onfirstline and len(this) == 1 and fcre.match(this[0]):
  368.                 this.append(part)
  369.                 linelen += partlen
  370.                 continue
  371.             if curlen + partlen > maxlen:
  372.                 if this:
  373.                     lines.append(joiner.join(this) + eol)
  374.                 
  375.                 if partlen > maxlen and ch != ' ':
  376.                     subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ')
  377.                     lines.extend(subl[:-1])
  378.                     this = [
  379.                         subl[-1]]
  380.                 else:
  381.                     this = [
  382.                         part]
  383.                 linelen = wslen + len(this[-1])
  384.                 maxlen = restlen
  385.                 continue
  386.             this.append(part)
  387.             linelen += partlen
  388.         
  389.         if this:
  390.             lines.append(joiner.join(this))
  391.             continue
  392.     
  393.     return lines
  394.  
  395.  
  396. def _binsplit(splittable, charset, maxlinelen):
  397.     i = 0
  398.     j = len(splittable)
  399.     while i < j:
  400.         m = i + j + 1 >> 1
  401.         chunk = charset.from_splittable(splittable[:m], True)
  402.         chunklen = charset.encoded_header_len(chunk)
  403.         if chunklen <= maxlinelen:
  404.             i = m
  405.             continue
  406.         j = m - 1
  407.     first = charset.from_splittable(splittable[:i], False)
  408.     last = charset.from_splittable(splittable[i:], False)
  409.     return (first, last)
  410.  
  411.